package com.neusiri.exp.controller;

import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import net.sf.jxls.exception.ParsePropertyException;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>用户信息Controller</p>
 * <p>创建日期：2020-04-29</p>
 *
 * @author 周群峰 zhou-qf_sr@neusiri.com
 */

@Controller
public class UserController {


    @RequestMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        //根据查询条件获取查询数据
        List<TestData> list = new ArrayList<>();
        for(int j = 0 ; j < 10 ; j++) {
            TestData td = new TestData(j, j * -1, "t" + j);
            list.add(td);;
        }

        // 表格使用的数据
        Map map = new HashMap<>(2);
        map.put("data", list);
        map.put("name","小明");

        Date date = new Date();
        SimpleDateFormat simpl = new SimpleDateFormat("yyyyMMddHHmmss");
        String currntTime = simpl.format(date);
        //导出列表名
        String fileName = "导出数据" + "_" + currntTime;

        //生成的导出文件
        File destFile = File.createTempFile(fileName, ".xlsx");

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            InputStream resourceAsStream = this.getClass().getResourceAsStream("/xls/test.xlsx");
            XLSTransformer xlsTransformer = new XLSTransformer();
            Workbook workbook = xlsTransformer.transformXLS(resourceAsStream, map);
            OutputStream os = new BufferedOutputStream(new FileOutputStream(destFile));
            workbook.write(os);
            resourceAsStream.close();
            os.flush();
            os.close();

            //将文件输入
            InputStream inputStream = new FileInputStream(destFile);
            // 设置response参数，可以打开下载页面
            response.reset();
            //设置响应文本格式
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xlsx").getBytes(), "iso-8859-1"));
            //将文件输出到页面
            ServletOutputStream out = response.getOutputStream();
            bis = new BufferedInputStream(inputStream);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            // 根据读取并写入
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (ParsePropertyException e) {
            //log.debug("导出失败：{}", e.getMessage());
        } catch (InvalidFormatException e) {
            //log.debug("导出失败：{}", e.getMessage());
        } finally {
            //使用完成后关闭流
            try {
                if (bis != null){
                    bis.close();
                }
                if (bos != null){
                    bos.close();
                }
            } catch (IOException e) {
                //log.debug("导出失败：{}",e.getMessage());
            }
        }
    }
}
